package com.bookstore.servlet;

import com.bookstore.pojo.User;
import com.bookstore.services.Impl.UserServiceImpl;
import com.bookstore.services.UserService;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "UserServlet", value = "/UserServlet")
public class UserServlet extends BaseServlet {
    UserService userService=  new UserServiceImpl();

    /**
     * 登录
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String readLine = request.getReader().readLine();
        HttpSession session = request.getSession();
        Gson gson=new Gson();
        User user = gson.fromJson(readLine, User.class);
        User login = userService.login(user);
        String json = gson.toJson(login);
        if(login!=null){
            response.setStatus(201);
            session.setAttribute("user",json);
            response.getWriter().write(json);
        }
    }

    protected void logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        session.removeAttribute("user");
        session.invalidate();
    }

    /**
     * 注册
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter writer = response.getWriter();
        String jsonUser = request.getParameter("user");
        System.out.println(jsonUser);
        Gson gson=new Gson();
        User user = gson.fromJson(jsonUser, User.class);
        if (user.getUsername()!=""&&user.getPassword()!=""&&user.getEmail()!="") {
            System.out.println("1:"+user);
            userService.registUser(user);
            response.setStatus(202);
        }
    }

    protected void updateUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void getUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        String user = (String) session.getAttribute("user");
        if(user!=null){
            System.out.println(user);
            response.getWriter().write(user);
        }
    }
}
